const Answer = require('../models/answers');
class AnswersCtl {

  // 检查答案的回答者是否存在（中间件）
  async checkAnswerExist(ctx, next) {
    const answer = await Answer.findById(ctx.params.id).select('+answerer')
    if (!answer) { ctx.throw(404, '回答不存在') }
    // 只有 删改查 答案时候检查此逻辑，赞、踩答案时候不检查
    if (ctx.params.questionId && ctx.params.questionId !== answer.questionId) {
      ctx.throw(404, '该问题下没有此答案');
    }

    // 存在state中下次就不用再一次去查询了
    ctx.state.answer = answer;
    await next();
  }

  // 检查一下是否是本人操作(中间件)
  async checkAnswerer(ctx, next) {
    const { answer } = ctx.state;
    if (answer.answerer.toString() !== ctx.state.user._id) { ctx.throw(403, '没有权限') }
    await next()
  }


  // 查询某个问题的答案列表(可分页)(可根据关键字查询)
  async find(ctx) {
    // 默认大小和页码

    const { page_size = 10 } = ctx.query;
    const { page = 1 } = ctx.query
    // 都要除去1 以下的数据
    const currentPage = Math.max(page * 1, 1);
    const pageSize = Math.max(page_size * 1, 1);
    const q = new RegExp(ctx.query.q, 'gi')
    ctx.body = await Answer
      .find({ content: q, questionId: ctx.params.questionId })
      .limit(pageSize)
      .skip((currentPage - 1) * pageSize);
  }

  // 查询指定的答案
  async findById(ctx) {
    const { field = '' } = ctx.query;
    const selectFields = (field.split(';').filter(f => f).map(f => ' +' + f).join('')) + " +createTime +updateTime"
    const answer = await Answer.findById(ctx.params.id).select(selectFields).populate('answerer')
    ctx.body = answer;
  }

  // 新建回答
  async create(ctx) {
    ctx.verifyParams({
      content: { type: 'string', required: true },
    });
    const answerer = ctx.state.user._id;
    const { questionId } = ctx.params;
    const answer = await new Answer({ ...ctx.request.body, answerer, questionId }).save();
    ctx.body = answer;
  }

  // 更新回答
  async update(ctx) {
    ctx.verifyParams({
      content: { type: 'string', required: false }
    })
    await ctx.state.answer.update(ctx.request.body);
    ctx.body = ctx.state.answer;
  }
  // 删除某个答案
  async delete(ctx) {
    await Answer.findByIdAndRemove(ctx.params.id);
    ctx.status = 204;
  }
}


module.exports = new AnswersCtl();